// 在main.js文件的全局作用域中添加以下变量定义
let currentPage = 1; // 当前页码，默认从第1页开始



const pageSize = 10; // 每页显示条数，可根据实际需求调整
// 全局变量用于跟踪当前播放的媒体
let currentPlayingAudio = null;
let currentPlayingVideoModal = null;

/**
 * 初始化媒体预览相关事件
 */
function initMediaPreviewEvents() {
    // 为查看详情按钮绑定事件（覆盖原有事件）
    $(document).off('click', '.view-btn').on('click', '.view-btn', function(e) {
        e.stopPropagation();
        const contentId = $(this).data('id');
        showMediaPreview(contentId);
    });
    
    // 为内容预览列绑定点击事件
    $(document).on('click', '#contentTableBody tr td:nth-child(3)', function(e) {
        e.stopPropagation();
        const contentId = $(this).closest('tr').find('.record-checkbox').data('id');
        showMediaPreview(contentId);
    });
    
    // 关闭媒体预览弹窗
    $('#closeMediaModal').on('click', hideMediaPreviewModal);
    
    // 点击弹窗背景关闭
    $('#mediaPreviewModal').on('click', function(e) {
        if (e.target === this) {
            hideMediaPreviewModal();
        }
    });
}

/**
 * 根据内容ID显示媒体预览
 * @param {string} contentId - 内容ID
 */
function showMediaPreview(contentId) {
    // 获取当前内容数据
    const $row = $(`#contentTableBody .record-checkbox[data-id="${contentId}"]`).closest('tr');
    const contentType = parseInt($row.find('td:nth-child(3) .rounded span').text() === '图片' ? 1 :
                           $row.find('td:nth-child(3) .rounded span').text() === '视频' ? 2 :
                           $row.find('td:nth-child(3) .rounded span').text() === '音频' ? 3 : 4);
    
    // 从数据中获取content_url，这里假设数据存储在row的data属性中
    // 实际应用中可能需要从数据源中获取
    const contentUrl = $row.data('content-url') || '';
    
    // 根据内容类型展示不同的预览方式
    switch(contentType) {
        case 1: // 图片
            showImagePreview(contentUrl);
            break;
        case 2: // 视频
            showVideoPreview(contentUrl);
            break;
        case 3: // 音频
            showAudioPlayer($row, contentUrl);
            break;
        case 4: // 文章
            showArticlePreview(contentUrl);
            break;
    }
}

/**
 * 显示图片预览
 * @param {string} url - 图片URL
 */
function showImagePreview(url) {
    // 隐藏其他类型容器，显示图片容器
    hideAllMediaContainers();
    $('#imageContainer').removeClass('hidden');
    $('#previewImage').attr('src', url);
    
    // 显示弹窗
    $('#mediaPreviewModal').removeClass('hidden').addClass('flex');
}

/**
 * 显示视频预览
 * @param {string} url - 视频URL
 */
function showVideoPreview(url) {
    // 如果有正在播放的视频弹窗，先关闭
    if (currentPlayingVideoModal) {
        hideMediaPreviewModal();
    }
    
    // 隐藏其他类型容器，显示视频容器
    hideAllMediaContainers();
    $('#videoContainer').removeClass('hidden');
    const $video = $('#previewVideo');
    $video.attr('src', url);
    $video[0].load();
    $video[0].play();
    
    // 记录当前播放的视频弹窗
    currentPlayingVideoModal = url;
    
    // 显示弹窗
    $('#mediaPreviewModal').removeClass('hidden').addClass('flex');
}

/**
 * 显示音频播放器
 * @param {jQuery} $row - 内容所在行的jQuery对象
 * @param {string} url - 音频URL
 */
function showAudioPlayer($row, url) {
    // 停止当前正在播放的音频
    if (currentPlayingAudio && currentPlayingAudio !== url) {
        stopAudioPlayback(currentPlayingAudioRow);
    }
    
    // 检查当前行是否已有音频播放器
    let $audioPlayer = $row.find('.audio-player');
    
    if (!$audioPlayer.length) {
        // 克隆音频播放器模板并添加到行中
        $audioPlayer = $('#audioPlayerTemplate').find('.audio-player').clone();
        $row.find('td:last-child').append($audioPlayer);
        
        // 设置音频源
        $audioPlayer.find('.audio-source').attr('src', url);
        
        // 绑定播放按钮事件
        $audioPlayer.find('.audio-play-btn').on('click', function() {
            toggleAudioPlayback($row);
        });
        
        // 绑定音频事件
        const $audio = $audioPlayer.find('.audio-source');
        $audio.on('timeupdate', function() {
            updateAudioProgress($row);
        });
        
        $audio.on('ended', function() {
            resetAudioPlayer($row);
            currentPlayingAudio = null;
            currentPlayingAudioRow = null;
        });
    }
    
    // 如果点击的是当前正在播放的音频，则暂停，否则播放
    if (currentPlayingAudio === url) {
        stopAudioPlayback($row);
        currentPlayingAudio = null;
        currentPlayingAudioRow = null;
    } else {
        startAudioPlayback($row);
        currentPlayingAudio = url;
        currentPlayingAudioRow = $row;
    }
}

/**
 * 显示文章预览
 * @param {string} url - 文章URL
 */
function showArticlePreview(url) {
    // 隐藏其他类型容器，显示文章容器
    hideAllMediaContainers();
    $('#articleContainer').removeClass('hidden');
    $('#articleIframe').attr('src', url);
    
    // 显示弹窗
    $('#mediaPreviewModal').removeClass('hidden').addClass('flex');
}

/**
 * 隐藏所有媒体容器
 */
function hideAllMediaContainers() {
    $('#imageContainer').addClass('hidden');
    $('#videoContainer').addClass('hidden');
    $('#articleContainer').addClass('hidden');
}

/**
 * 隐藏媒体预览弹窗
 */
function hideMediaPreviewModal() {
    // 停止视频播放
    const $video = $('#previewVideo');
    if (!$('#videoContainer').hasClass('hidden')) {
        $video[0].pause();
        $video.attr('src', '');
    }
    
    // 重置当前播放的视频
    currentPlayingVideoModal = null;
    
    // 隐藏弹窗
    $('#mediaPreviewModal').removeClass('flex').addClass('hidden');
    hideAllMediaContainers();
}

/**
 * 开始音频播放
 * @param {jQuery} $row - 内容所在行的jQuery对象
 */
function startAudioPlayback($row) {
    const $audioPlayer = $row.find('.audio-player');
    const $audio = $audioPlayer.find('.audio-source')[0];
    const $playBtn = $audioPlayer.find('.audio-play-btn');
    
    $audio.play();
    $playBtn.html('<i class="fa fa-pause"></i>');
}

/**
 * 停止音频播放
 * @param {jQuery} $row - 内容所在行的jQuery对象
 */
function stopAudioPlayback($row) {
    const $audioPlayer = $row.find('.audio-player');
    const $audio = $audioPlayer.find('.audio-source')[0];
    const $playBtn = $audioPlayer.find('.audio-play-btn');
    
    $audio.pause();
    $playBtn.html('<i class="fa fa-play"></i>');
}

/**
 * 切换音频播放状态
 * @param {jQuery} $row - 内容所在行的jQuery对象
 */
function toggleAudioPlayback($row) {
    const $audio = $row.find('.audio-source')[0];
    if ($audio.paused) {
        startAudioPlayback($row);
    } else {
        stopAudioPlayback($row);
    }
}

/**
 * 更新音频进度条
 * @param {jQuery} $row - 内容所在行的jQuery对象
 */
function updateAudioProgress($row) {
    const $audioPlayer = $row.find('.audio-player');
    const $audio = $audioPlayer.find('.audio-source')[0];
    const $progressBar = $audioPlayer.find('.audio-progress-bar');
    const $timeDisplay = $audioPlayer.find('.audio-time');
    
    const progress = ($audio.currentTime / $audio.duration) * 100;
    $progressBar.css('width', `${progress}%`);
    
    // 格式化时间显示
    const minutes = Math.floor($audio.currentTime / 60);
    const seconds = Math.floor($audio.currentTime % 60);
    $timeDisplay.text(`${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`);
}

/**
 * 重置音频播放器状态
 * @param {jQuery} $row - 内容所在行的jQuery对象
 */
function resetAudioPlayer($row) {
    const $audioPlayer = $row.find('.audio-player');
    const $audio = $audioPlayer.find('.audio-source')[0];
    const $playBtn = $audioPlayer.find('.audio-play-btn');
    const $progressBar = $audioPlayer.find('.audio-progress-bar');
    const $timeDisplay = $audioPlayer.find('.audio-time');
    
    $audio.currentTime = 0;
    $playBtn.html('<i class="fa fa-play"></i>');
    $progressBar.css('width', '0%');
    $timeDisplay.text('00:00');
}


/**
 * 获取媒体内容列表数据
 * @param {Object} params - 查询参数
 * @param {string} params.claimStatus - 认领状态：1、未认领；2、已被认领'
 * @param {string} params.contentType - 内容类型（全部类型/图片/视频/音频/文档）
 * @param {string} params.status - 审核状态（待审核/审核通过/审核拒绝/再次审核/全部状态）
 * @param {string} params.sort - 排序方式（默认排序/提交时间 降序/提交时间 升序/优先级 高到低/优先级 低到高）
 * @param {string} params.keyword - 内容ID/关键词
 * @param {string} params.submitter - 提交者
 * @param {string} params.startDate - 开始日期
 * @param {string} params.endDate - 结束日期
 * @param {string} params.violationType - 疑似违规类型
 * @param {number} params.page - 页码
 * @param {number} params.pageSize - 每页条数
 * @returns {Promise<Object>} 包含列表数据和分页信息的对象
 */
async function fetchMediaContentList(params) {
    try {
        // 构建查询字符串
        const queryParams = new URLSearchParams();
        Object.entries(params).forEach(([key, value]) => {
            if (value !== undefined && value !== null && value !== '') {
                queryParams.append(key, value);
            }
        });

        // 发起请求
        const response = await fetch(`/system/GetMediaListFoPage?${queryParams.toString()}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                // 根据实际需求添加认证信息
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });
        // console.log(response)
        if (response.status/1 != 200) {
            throw new Error(`请求失败: ${response.statusText}`);
        }

        const data = await response.json();
        // console.log(data)
        return data;
    } catch (error) {
        // console.error('获取媒体内容列表失败:', error);
        // 可以在这里添加错误提示逻辑，如显示 Toast 等
        // throw error; // 抛出错误供调用者处理
        showToast(error.message || '获取媒体内容列表失败');
    }
}

/**
 * 获取页面统计数据
 * */
function getPageStats(){
    $.ajax({
        url: '/system/GetMediaStats',
        type: 'GET',
        dataType: 'json',
        headers: {
            'Content-Type': 'application/json',
            // 根据实际需求添加认证信息
            'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        success: function(result) {
            if(result.status/1 == 0){
                // console.log(result.data)
                $('#totalCount').text(result.data.pending.total)
                var totalClaimed = result.data.pending.trend
                var percent = result.data.pending.percent

                var totalClaimedTotal = result.data.audited.total
                var totalClaimedPercent = result.data.audited.percent
                var totalClaimedTrend = result.data.audited.trend
                $('#totalClaimedTotal').text(totalClaimedTotal)

                var totalViolationTotal = result.data.violation.total
                var totalViolationPercent = result.data.violation.percent
                var totalViolationTrend = result.data.violation.trend
                $('#totalViolationTotal').text(totalViolationTotal)

                var totalAvgHandleTimeTotal = result.data.avgHandleTime.minutes
                var totalAvgHandleTimePercent = result.data.avgHandleTime.percent
                var totalAvgHandleTimeTrend = result.data.avgHandleTime.trend
                $('#totalAvgHandleTime').text(totalAvgHandleTimeTotal+"分钟")

                if(totalClaimed/1 == 0){
                    var _html = `
                    <span class="text-info flex items-center" >
                        <i class="fa fa-arrows-h mr-1"></i> ${percent}%
                    </span>
                    <span class="text-neutral-400 ml-2">较昨日</span>
                    `
                    $('#totalClaimedHtml').html(_html)
                }else if(totalClaimed/1 == 1){
                    var _html = `
                    <span class="text-danger flex items-center" >
                        <i class="fa fa-arrow-up mr-1"></i> ${percent}%
                    </span>
                    <span class="text-neutral-400 ml-2">较昨日</span>
                    `
                    $('#totalClaimed').html(_html)
                }else if(totalClaimed/1 == -1){
                    var _html = `
                    <span class="text-success flex items-center" >
                        <i class="fa fa-arrow-down mr-1"></i> ${percent}%
                    </span>
                    <span class="text-neutral-400 ml-2">较昨日</span>
                    `
                    $('#totalClaimed').html(_html)
                }

                if(totalClaimedTrend/1 == 0){
                    var _html = `
                    <span class="text-info flex items-center" >
                        <i class="fa fa-arrows-h mr-1"></i> ${totalClaimedPercent}%
                    </span>
                    <span class="text-neutral-400 ml-2">较昨日</span>
                    `
                    $('#totalClaimedPercent').html(_html)
                }else if(totalClaimedTrend/1 == 1){
                    var _html = `
                    <span class="text-danger flex items-center" >
                        <i class="fa fa-arrow-up mr-1"></i> ${totalClaimedPercent}%
                    </span>
                    <span class="text-neutral-400 ml-2">较昨日</span>
                    `
                    $('#totalClaimedPercent').html(_html)
                }else if(totalClaimedTrend/1 == -1){
                    var _html = `
                    <span class="text-success flex items-center" >
                        <i class="fa fa-arrow-down mr-1"></i> ${totalClaimedPercent}%
                    </span>
                    <span class="text-neutral-400 ml-2">较昨日</span>
                    `
                    $('#totalClaimedPercent').html(_html)
                }

                if(totalViolationTrend/1 == 0){
                    var _html = `
                    <span class="text-info flex items-center" >
                        <i class="fa fa-arrows-h mr-1"></i> ${totalViolationPercent}%
                    </span>
                    <span class="text-neutral-400 ml-2">较昨日</span>
                    `
                    $('#totalViolationPercent').html(_html)
                }else if(totalViolationTrend/1 == 1){
                    var _html = `
                    <span class="text-danger flex items-center" >
                        <i class="fa fa-arrow-up mr-1"></i> ${totalViolationPercent}%
                    </span>
                    <span class="text-neutral-400 ml-2">较昨日</span>
                    `
                    $('#totalViolationPercent').html(_html)
                }else if(totalViolationTrend/1 == -1){
                    var _html = `
                    <span class="text-success flex items-center" >
                        <i class="fa fa-arrow-down mr-1"></i> ${totalViolationPercent}%
                    </span>
                    <span class="text-neutral-400 ml-2">较昨日</span>
                    `
                    $('#totalViolationPercent').html(_html)
                }
                if(totalAvgHandleTimeTrend/1 == 0){
                    var _html = `
                    <span class="text-info flex items-center" >
                        <i class="fa fa-arrows-h mr-1"></i> ${totalAvgHandleTimePercent}%
                    </span>
                    <span class="text-neutral-400 ml-2">较昨日</span>
                    `
                    $('#totalAvgHandleTimeTrend').html(_html)
                }else if(totalAvgHandleTimeTrend/1 == 1){
                    var _html = `
                    <span class="text-danger flex items-center" >
                        <i class="fa fa-arrow-up mr-1"></i> ${totalAvgHandleTimePercent}%
                    </span>
                    <span class="text-neutral-400 ml-2">较昨日</span>
                    `
                    $('#totalAvgHandleTimeTrend').html(_html)
                }else if(totalAvgHandleTimeTrend/1 == -1){
                    var _html = `
                    <span class="text-success flex items-center" >
                        <i class="fa fa-arrow-down mr-1"></i> ${totalAvgHandleTimePercent}%
                    </span>
                    <span class="text-neutral-400 ml-2">较昨日</span>
                    `
                    $('#totalAvgHandleTimeTrend').html(_html)
                }
            }
        },
        error: function(xhr, status, error) {
            console.error('获取页面统计数据失败:', error);
            showToast('获取页面统计数据失败');
        }
    })
}

function init() {
    // 加载列表数据
    loadMediaList();
    
    // 绑定事件
    bindEvents();

    // 获取页面统计数据
    getPageStats();

    // 添加新的初始化函数
    initMediaPreviewEvents();
}

/**
 * 获取筛选参数
 */
function getFilterParams() {
    return {
        page: currentPage,
        pageSize: pageSize,
        claimStatus: $('#claimStatusFilter').val(),
        contentType: $('#contentTypeFilter').val(),
        status: $('#statusFilter').val(),
        sort: $('#sortFilter').val(),
        keyword: $('#keywordSearch').val().trim(),
        submitter: $('#submitterSearch').val().trim(),
        startDate: $('#startDate').val(),
        endDate: $('#endDate').val(),
        violationType: $('#violationTypeFilter').val()
    };
}

/**
 * 加载媒体内容列表
 */
function loadMediaList() {
    // 显示加载中状态
    $('#contentTableBody').html('<tr><td colspan="8" class="text-center py-4">加载中...</td></tr>');
    
    // 获取筛选参数
    const params = getFilterParams();
    
    // 调用后端接口获取数据
    fetchMediaContentList(params)
        .then(result => {
            renderTable(result.data.list);
            renderPagination(result.data.total, currentPage, pageSize);
            updateSelectedCount();
            updateBatchButtons();
        })
        .catch(error => {
            // console.error('加载数据失败:', error);
            $('#contentTableBody').html('<tr><td colspan="8" class="text-center py-4 text-danger">加载数据失败，请重试</td></tr>');
        });
}

/**
 * 渲染表格数据
 * @param {Array} data - 媒体内容数据数组
 */
function renderTable(data) {
    const $tbody = $('#contentTableBody');
    $tbody.empty();
    
    if (data.length === 0) {
        $tbody.html('<tr><td colspan="8" class="text-center py-4">没有找到匹配的数据</td></tr>');
        return;
    }
    
    data.forEach(item => {
        // 构建内容预览HTML
        let previewHtml = '';
        let contentTypeText = '';
        switch (item.content_type/1) {
            case 1:
                contentTypeText = '图片';
                previewHtml = `
                    <div class="relative w-20 h-14 rounded overflow-hidden border border-neutral-200">
                        <img src="${item.content_url}" alt="${item.title}" class="w-full h-full object-cover">
                        <span class="absolute top-1 right-1 bg-primary/90 text-white text-xs px-1.5 py-0.5 rounded">${contentTypeText}</span>
                    </div>
                `;
                break;
            case 2:
                contentTypeText = '视频';
                // 优先使用cover_url，如果没有则使用默认图片
                const videoCover = item.cover_url ? item.cover_url : 'https://picsum.photos/id/1035/100/70';
                previewHtml = `
                    <div class="relative w-20 h-14 rounded overflow-hidden border border-neutral-200">
                        <img src="${videoCover}" alt="${item.title}" class="w-full h-full object-cover">
                        <span class="absolute top-1 right-1 bg-primary/90 text-white text-xs px-1.5 py-0.5 rounded">${contentTypeText}</span>
                        <div class="absolute inset-0 bg-black/30 flex items-center justify-center">
                            <i class="fa fa-play text-white"></i>
                        </div>
                    </div>
                `;
                break;
            case 3:
                contentTypeText = '音频';
                previewHtml = `
                    <div class="relative w-20 h-14 rounded overflow-hidden border border-neutral-200 bg-neutral-100 flex items-center justify-center">
                        <i class="fa fa-file-audio-o text-neutral-400 text-xl"></i>
                        <span class="absolute top-1 right-1 bg-primary/90 text-white text-xs px-1.5 py-0.5 rounded">${contentTypeText}</span>
                    </div>
                `;
                break;
            case 4:
                contentTypeText = '文档';
                previewHtml = `
                    <div class="relative w-20 h-14 rounded overflow-hidden border border-neutral-200 bg-neutral-100 flex items-center justify-center">
                        <i class="fa fa-file-text-o text-neutral-400 text-xl"></i>
                        <span class="absolute top-1 right-1 bg-primary/90 text-white text-xs px-1.5 py-0.5 rounded">${contentTypeText}</span>
                    </div>
                `;
                break;
            default:
                contentTypeText = '未知';
                previewHtml = `
                    <div class="relative w-20 h-14 rounded overflow-hidden border border-neutral-200 bg-neutral-100 flex items-center justify-center">
                        <i class="fa fa-question text-neutral-400 text-xl"></i>
                        <span class="absolute top-1 right-1 bg-primary/90 text-white text-xs px-1.5 py-0.5 rounded">${contentTypeText}</span>
                    </div>
                `;
        }
        
        // 构建AI预审结果HTML
        let aiResultHtml = '';
        switch (item.ai_preview_result/1) {
            case 1:
                aiResultHtml = `
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-success/10 text-success">
                        <i class="fa fa-check mr-1"></i> 通过
                    </span>
                `;
                break;
            case 2:
                aiResultHtml = `
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-warning/10 text-warning">
                        <i class="fa fa-question mr-1"></i> 疑似
                    </span>
                `;
                break;
            case 3:
                aiResultHtml = `
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-danger/10 text-danger">
                        <i class="fa fa-times mr-1"></i> 违规
                    </span>
                `;
                break;
            default:
                aiResultHtml = `
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-neutral-100 text-neutral-500">
                        <i class="fa fa-question mr-1"></i> 未知
                    </span>
                `;
        }
        
        // 构建AI预审补充信息
        //  `ai_preview_result` tinyint(1) NOT NULL COMMENT 'AI预审结果（1：通过/2：疑似/3：违规，用tinyint节省空间）'
        let aiExtraHtml = '';                    
        if (item.ai_preview_result === 1) {
            aiExtraHtml = `<p class="text-xs text-neutral-500 mt-1">置信度: ${item.ai_confidence}</p>`;
        } else if (item.ai_preview_result === 2 || item.ai_preview_result === 3) {
            aiExtraHtml = `
                <p class="text-xs text-neutral-500 mt-1">可能包含: ${item.ai_suspect_type}</p>
                <p class="text-xs text-neutral-500">置信度: ${item.ai_confidence}</p>
            `;
        }
        
        // 构建认领状态HTML
        let claimStatusHtml = '';
        if (item.claimed_status/1 === 2) {
            claimStatusHtml = `
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-primary/10 text-primary">
                    <i class="fa fa-unlock mr-1"></i> 已认领
                </span>
                <p class="text-xs text-neutral-500 mt-1">${item.claimed_by_name || '未知'}</p>
            `;
        } else {
            claimStatusHtml = `
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-neutral-100 text-neutral-500">
                    <i class="fa fa-lock mr-1"></i> 未认领
                </span>
            `;
        }
        
        // 构建优先级HTML
        let priorityHtml = '';
        switch (item.priority/1) {
            case 3:
                priorityHtml = `<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-danger/10 text-danger mt-1">高优先级</span>`;
                break;
            case 2:
                priorityHtml = `<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-warning/10 text-warning mt-1">中优先级</span>`;
                break;
            case 1:
                priorityHtml = `<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-neutral-100 text-neutral-500 mt-1">低优先级</span>`;
                break;
            default:
                priorityHtml = `<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-neutral-100 text-neutral-500 mt-1">未知优先级</span>`;
        }
        
        // 构建操作按钮HTML（已认领的内容不能再认领）
        let actionButtons = `
            <button class="text-primary hover:text-primary/80 view-btn" title="查看详情" data-id="${item.content_id}">
                <i class="fa fa-eye"></i>
            </button>
            <button class="text-success hover:text-success/80 approve-btn" title="通过" data-id="${item.content_id}">
                <i class="fa fa-check"></i>
            </button>
            <button class="text-danger hover:text-danger/80 reject-btn" title="拒绝" data-id="${item.content_id}">
                <i class="fa fa-times"></i>
            </button>
            <button class="text-neutral-500 hover:text-neutral-700 review-btn" title="标记待复查" data-id="${item.content_id}">
                <i class="fa fa-flag"></i>
            </button>
        `;
        
        if (item.claimStatus === '未认领') {
            actionButtons = `
                <button class="text-primary hover:text-primary/80 claim-btn" title="认领任务" data-id="${item.content_id}">
                    <i class="fa fa-hand"></i>
                </button>
                ${actionButtons}
            `;
        }
        // 构建审核状态html
        let reviewStatusHtml = '';
        // audit_status审核状态（1：待审核/2：审核通过/31：拒绝-涉黄/32：拒绝-涉政/33：拒绝-广告/34：拒绝-其他/4：再次审核，细化状态）
        switch (item.audit_status/1) {
            case 1:
                reviewStatusHtml = `
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-warning/10 text-warning">
                        <i class="fa fa-question mr-1"></i> 待审核
                    </span>
                `;
                break;
            case 2:
                reviewStatusHtml = `
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-success/10 text-success">
                        <i class="fa fa-check mr-1"></i> 审核通过
                    </span>
                `;
                break;
            case 31:
                reviewStatusHtml = `
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-danger/10 text-danger">
                        <i class="fa fa-times mr-1"></i> 拒绝-涉黄
                    </span>
                `;
                break;
            case 32:
                reviewStatusHtml = `
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-danger/10 text-danger">
                        <i class="fa fa-times mr-1"></i> 拒绝-涉政
                    </span>
                `;
                break;
            case 33:
                reviewStatusHtml = `
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-danger/10 text-danger">
                        <i class="fa fa-times mr-1"></i> 拒绝-广告
                    </span>
                `;
                break;
            case 34:
                reviewStatusHtml = `
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-danger/10 text-danger">
                        <i class="fa fa-times mr-1"></i> 拒绝-其他
                    </span>
                `;
                break;
            case 4:
                reviewStatusHtml = `
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-warning/10 text-warning">
                        <i class="fa fa-flag mr-1"></i> 再次审核
                    </span>
                `;
                break;
            default:
                reviewStatusHtml = `
                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-neutral-100 text-neutral-500">
                        <i class="fa fa-question mr-1"></i> 未知状态
                    </span>
                `;
                break;
        }

        
        // 构建行HTML
        const row = `
            <tr class="hover:bg-neutral-50 transition-colors" data-content-url="${item.content_url}">
                <td class="px-5 py-4">
                    <input type="checkbox" class="record-checkbox rounded border-neutral-300 text-primary focus:ring-primary" data-id="${item.content_id}">
                </td>
                <td class="px-5 py-4 text-sm">#${item.content_id}</td>
                <td class="px-5 py-4">
                    <div class="flex items-center">
                        ${previewHtml}
                    </div>
                </td>
                <td class="px-5 py-4">
                    <p class="text-sm font-medium line-clamp-1">${item.title}</p>
                    <p class="text-xs text-neutral-500 mt-1">分类: ${item.category}</p>
                </td>
                <td class="px-5 py-4">
                    ${claimStatusHtml}
                </td>
                <td class="px-5 py-4">
                    ${reviewStatusHtml}
                </td>
                <td class="px-5 py-4">
                    ${aiResultHtml}
                    ${aiExtraHtml}
                </td>
                <td class="px-5 py-4">
                    <p class="text-sm">用户ID: ${item.submit_user_id}</p>
                    ${item.submit_user_nickname ? `<p class="text-xs text-neutral-500 mt-0.5">昵称: ${item.submit_user_nickname}</p>` : ''}
                    <p class="text-xs text-neutral-500 mt-0.5">${item.submit_time}</p>
                    ${item.platform ? `<p class="text-xs text-neutral-500 mt-0.5">来源: ${item.platform} ${item.channel ? '-' + item.channel : ''}</p>` : ''}
                    ${priorityHtml}
                </td>
                <td class="px-5 py-4">
                    <div class="flex space-x-2">
                        ${actionButtons}
                    </div>
                </td>
            </tr>
        `;
        
        $tbody.append(row);
    });
}

/**
 * 渲染分页控件
 * @param {number} total - 总记录数
 * @param {number} currentPage - 当前页码
 * @param {number} pageSize - 每页条数
 */
function renderPagination(total, currentPage, pageSize) {
    const totalPages = Math.ceil(total / pageSize);
    const paginationContainer = $('.flex.space-x-1'); // 分页容器
    
    // 清空现有分页
    paginationContainer.empty();
    
    // 上一页按钮
    const prevDisabled = currentPage === 1 ? 'disabled' : '';
    paginationContainer.append(`
        <button class="w-8 h-8 flex items-center justify-center rounded border border-neutral-200 text-neutral-400 hover:border-primary hover:text-primary disabled:opacity-50 pagination-btn" 
                data-page="${currentPage - 1}" ${prevDisabled}>
            <i class="fa fa-angle-left"></i>
        </button>
    `);
    
    // 页码按钮（最多显示5个页码）
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, startPage + 4);
    
    // 调整显示范围
    if (endPage - startPage < 4 && totalPages > 5) {
        startPage = Math.max(1, endPage - 4);
    }
    
    for (let i = startPage; i <= endPage; i++) {
        const isActive = i === currentPage ? 'border-primary bg-primary text-white' : 'border-neutral-200 text-neutral-700 hover:border-primary hover:text-primary';
        paginationContainer.append(`
            <button class="w-8 h-8 flex items-center justify-center rounded ${isActive} pagination-btn" data-page="${i}">
                ${i}
            </button>
        `);
    }
    
    // 下一页按钮
    const nextDisabled = currentPage === totalPages ? 'disabled' : '';
    paginationContainer.append(`
        <button class="w-8 h-8 flex items-center justify-center rounded border border-neutral-200 text-neutral-400 hover:border-primary hover:text-primary disabled:opacity-50 pagination-btn" 
                data-page="${currentPage + 1}" ${nextDisabled}>
            <i class="fa fa-angle-right"></i>
        </button>
    `);
    
    // 更新分页信息
    const start = total > 0 ? (currentPage - 1) * pageSize + 1 : 0;
    const end = Math.min(currentPage * pageSize, total);
    $('.pagenation').text(`显示 ${start} 至 ${end} 条，共 ${total} 条`);
}

/**
 * 重置筛选条件
 */
function resetFilters() {
    $('#contentTypeFilter').val('全部类型');
    $('#statusFilter').val('待审核');
    $('#sortFilter').val('默认排序');
    $('#keywordSearch').val('');
    $('#submitterSearch').val('');
    $('#startDate').val('');
    $('#endDate').val('');
    $('#violationTypeFilter').val('全部类型');
    $('#selectAll').prop('checked', false);
}

/**
 * 更新批量操作按钮状态
 */
function updateBatchButtons() {
    const selectedCount = $('.record-checkbox:checked').length;
    const buttons = $('#batchClaimBtn, #batchApproveBtn, #batchRejectBtn, #batchReviewBtn');
    
    if (selectedCount > 0) {
        buttons.removeAttr('disabled');
    } else {
        buttons.attr('disabled', 'disabled');
    }
}

/**
 * 更新已选择数量显示
 */
function updateSelectedCount() {
    const count = $('.record-checkbox:checked').length;
    $('#selectedCount').text(`已选择 ${count} 项`);
}

/**
 * 获取选中的内容ID列表
 * @returns {Array} 选中的ID数组
 */
function getSelectedContentIds() {
    const ids = [];
    $('.record-checkbox:checked').each(function() {
        const id = $(this).data('id');
        if (id) ids.push(id);
    });
    return ids;
}
/**
 * 设置单行选中
 * @param {*} content_id 
 */
function setItemChecked(content_id){
    $('.record-checkbox').each(function() {
        const id = $(this).data('id');
        if (id === content_id) {
            $(this).prop('checked', true).trigger('change');
        }
    });
    // 强制更新全选框状态和批量按钮状态
    const allChecked = $('.record-checkbox:checked').length === $('.record-checkbox').length;
    $('#selectAll').prop('checked', allChecked);
    updateBatchButtons();
    updateSelectedCount();
}

/**
 * 处理批量认领
 */
function handleBatchClaim() {
    const ids = getSelectedContentIds();
    if (ids.length === 0) {
        showToast('请选择要认领的记录');
        return;
    }
    
    // 调用后端API进行批量认领
    batchOperate(ids, 'claim')
        .then(() => {
            loadMediaList(); // 重新加载列表
            alert('批量认领成功');
        })
        .catch(error => {
            // console.error('批量认领失败:', error);
            alert('批量认领失败，请重试');
        });
}

/**
 * 处理批量通过
 */
function handleBatchApprove() {
    const ids = getSelectedContentIds();
    if (ids.length === 0) {
        showToast('请选择要通过的记录', 'warning');
        return;
    }

    batchOperate(ids, 'approve')
            .then(() => {
                showToast('批量通过成功', 'success');
                loadMediaList(); // 重新加载列表
                resetBatchOperationState(); // 重置选择状态
            })
            .catch(error => {
                showToast(`批量通过失败: ${error.message || '未知错误'}`, 'error');
            });
}

/**
 * 处理批量标记复查
 */
function handleBatchReview() {
    showReviewModal();
}

/**
 * 处理单个认领
 */
function handleClaim(contentId) {
    operateSingle(contentId, 'claim')
            .then(() => {
                loadMediaList();
                showToast('认领成功', 'success');
            })
            .catch(error => {
                // console.error('认领失败:', error);
                showToast('认领失败', 'error');
            });
}

/**
 * 处理单个通过
 */
function handleApprove(contentId) {
    operateSingle(contentId, 'approve')
            .then(() => {
                loadMediaList();
                showToast('审核通过成功', 'success');
            })
            .catch(error => {
                // console.error('审核通过失败:', error);
                showToast('审核通过失败', 'error');
            });
}

/**
 * 处理单个拒绝
 */
async function handleReject(contentId) {
    // 选中当前行的复选框
    setItemChecked(contentId);
    // 强制更新选中记录和按钮状态
    updateSelectedRecords();
    
    showRejectModal();
    
    try {
        // 等待用户选择拒绝类型并确认
        await batchOperate([contentId], 'reject');
        showToast('批量拒绝成功', 'success');
        loadMediaList(); // 重新加载列表
        resetBatchOperationState(); // 重置选择状态
        $('#rejectRemark').val(''); // 清空备注
        hideRejectModal();
    } catch (error) {
        // 如果是用户取消选择拒绝类型，不显示错误提示
        if (error.message !== '请选择拒绝类型') {
            showToast(`批量拒绝失败: ${error.message || '未知错误'}`, 'error');
        }
        hideRejectModal();
    }
}

/**
 * 处理单个标记复查
 */
function handleReview(contentId) {
    // 选中当前行的复选框
    setItemChecked(contentId);
    // 强制更新选中记录和按钮状态
    updateSelectedRecords();
    // 显示复查模态框
    showReviewModal();
}

/**
 * 单个操作API调用
 */
async function operateSingle(contentId, action) {
    try {
        let url = '';
        let requestData = { ids: [contentId] };

        switch(action) {
            case 'approve':
                url = '/system/BatchAuditPass';
                break;
            case 'reject':
                url = '/system/BatchAuditReject';
                // 获取拒绝类型（通过模态框）
                const rejectType = await getRejectType();
                if (!rejectType) {
                    throw new Error('请选择拒绝类型');
                }
                requestData.rejectType = rejectType;
                requestData.remark = $('#rejectRemark').val().trim() || '';
                break;
            case 'review':  // 添加复查操作支持
                url = '/system/BatchMarkReview';  // 假设的后端API地址
                requestData.remark = $('#reviewRemark').val() || '';  // 可选备注
                break;
            case 'claim':  // 添加认领操作支持
                url = '/system/BatchClaim';  // 假设的后端API地址
                requestData.remark = $('#claimRemark').val() || '';  // 可选备注
                break;
            default:
                throw new Error('不支持的操作类型');
        }

        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify(requestData)
        });

        const result = await response.json();
        
        if (!response.ok || result.status/1 !== 0) {
            throw new Error(result.message || `操作失败: ${response.statusText}`);
        }
        
        return result;
    } catch (error) {
        // console.error(`批量${action}操作失败:`, error);
        // throw error; // 抛出错误给调用方处理
        showToast(error.msg || '操作失败');
    }
}

/**
 * 批量操作通用方法
 * @param {Array} ids - 内容ID数组
 * @param {string} action - 操作类型(approve/reject)
 * @returns {Promise}
 */
async function batchOperate(ids, action) {
    try {
        let url = '';
        let requestData = { ids: ids };

        switch(action) {
            case 'approve':
                url = '/system/BatchAuditPass';
                break;
            case 'reject':
                url = '/system/BatchAuditReject';
                // 获取拒绝类型（通过模态框）
                const rejectType = await getRejectType();
                if (!rejectType) {
                    throw new Error('请选择拒绝类型');
                }
                requestData.rejectType = rejectType;
                requestData.remark = $('#rejectRemark').val().trim() || '';
                break;
            case 'review':  // 添加复查操作支持
                url = '/system/BatchMarkReview';  // 假设的后端API地址
                requestData.remark = $('#reviewRemark').val() || '';  // 可选备注
                break;
            case 'claim':  // 添加认领操作支持
                url = '/system/BatchClaim';  // 假设的后端API地址
                requestData.remark = $('#claimRemark').val() || '';  // 可选备注
                break;
            default:
                throw new Error('不支持的操作类型');
        }

        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify(requestData)
        });

        const result = await response.json();
        
        if (!response.ok || result.status/1 !== 0) {
            throw new Error(result.msg || `操作失败: ${response.statusText}`);
        }
        
        return result;
    } catch (error) {
        throw error; // 抛出错误给调用方处理
    }
}

/**
 * 日期格式化辅助函数
 * @param {string|Date} date - 日期对象或字符串
 * @returns {string} - 格式化后的日期字符串（YYYY-MM-DD HH:MM）
 */
function formatDate(date) {
    if (!date) return '';
    const d = new Date(date);
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
}

/**
 * 查看详情
 */
function viewDetail(contentId) {
    // 跳转到详情页或打开详情弹窗
    // window.location.href = `media_detail.html?id=${contentId}`;
}


function updateSelectedRecords() {
    selectedRecords = [];
    $('.record-checkbox:checked').each(function() {
        const recordId = $(this).data('id'); // 兼容两种获取方式
        if (recordId) {
            selectedRecords.push(recordId);
        }
    });
    // console.log(selectedRecords)
    $('#selectedCount').text(`已选择 ${selectedRecords.length} 项`);
    const hasSelection = selectedRecords.length > 0;
    $('#batchClaimBtn, #batchApproveBtn, #batchRejectBtn, #batchReviewBtn').prop('disabled', !hasSelection);
}

function resetBatchOperationState() {
    selectedRecords = [];
    currentContentId = '';
    currentAction = '';
    isBatchOperation = false;
    currentClaimId = '';
    
    $('#selectAll').prop('checked', false);
    $('.record-checkbox').prop('checked', false);
    updateSelectedRecords();
}

// 显示拒绝模态框
function showRejectModal() {
    $('#rejectModal').removeClass('hidden').addClass('flex');
}

// 隐藏拒绝模态框
function hideRejectModal() {
    $('#rejectModal').removeClass('flex').addClass('hidden');
}

/**
 * 处理批量拒绝
 */
async function handleBatchReject() {
    const ids = getSelectedContentIds();
    if (ids.length === 0) {
        showToast('请选择要拒绝的记录', 'warning');
        return;
    }
    
    showRejectModal();
    
    try {
        // 等待用户选择拒绝类型并确认
        await batchOperate(ids, 'reject');
        showToast('批量拒绝成功', 'success');
        loadMediaList(); // 重新加载列表
        resetBatchOperationState(); // 重置选择状态
        $('#rejectRemark').val(''); // 清空备注
        hideRejectModal();
    } catch (error) {
        // 如果是用户取消选择拒绝类型，不显示错误提示
        if (error.message !== '请选择拒绝类型') {
            showToast(`批量拒绝失败: ${error.message || '未知错误'}`, 'error');
        }
        hideRejectModal();
    }
}

/**
 * 获取拒绝类型（通过模态框选择）
 * @returns {Promise<string>} 拒绝类型
 */
function getRejectType() {
    return new Promise((resolve) => {
        try {
            // 先解绑原有事件，避免重复绑定
            $('#confirmReject').off('click');
            $('#cancelReject').off('click');
            $('#closeRejectModal').off('click');
            
            // 确认按钮事件
            $('#confirmReject').on('click', function() {
                const selectedType = $('#rejectTypeSelect').val();
                hideRejectModal();
                resolve(selectedType);
            });
            
            // 取消按钮事件
            $('#cancelReject').on('click', function() {
                hideRejectModal();
                resolve(null);
            });
            
            // 关闭按钮事件
            $('#closeRejectModal').on('click', function() {
                hideRejectModal();
                resolve(null);
            });
        } catch (error) {
            // console.error('获取拒绝类型失败:', error);
            resolve(null);
        }
    });
}

// 显示复查模态框
function showReviewModal() {
    $('#reviewModal').removeClass('hidden').addClass('flex');
}

// 隐藏复查模态框
function hideReviewModal() {
    $('#reviewModal').removeClass('flex').addClass('hidden');
    // 取消所有选中状态并触发更新
    $('.record-checkbox').prop('checked', false).trigger('change');
    $('#selectAll').prop('checked', false);
}

function handleConfirmReview() {
    const ids = getSelectedContentIds();
    if (ids.length === 0) {
        showToast('请选择要标记复查的记录', 'warning');
        return;
    }
    // 显示确认对话框
    batchOperate(ids, 'review')
            .then(() => {
                showToast('批量标记复查成功', 'success');
                loadMediaList(); // 重新加载列表
                resetBatchOperationState(); // 重置选择状态
            })
            .catch(error => {
                showToast(`批量标记复查失败: ${error.message || '未知错误'}`, 'error');
            });
}

/**
 * 绑定页面所有事件
 */
function bindEvents() {
    // 筛选按钮点击事件
    $('#filterBtn').on('click', function() {
        currentPage = 1; // 重置为第一页
        loadMediaList();
    });
    
    // 重置按钮点击事件
    $('#resetBtn').on('click', function() {
        resetFilters();
        currentPage = 1;
        loadMediaList();
    });
    
    // 全选复选框事件
    $('#selectAll').on('change', function() {
        const isChecked = $(this).prop('checked');
        // $('.record-checkbox').prop('checked', isChecked);
        // updateBatchButtons();
        $('.record-checkbox').prop('checked', isChecked).trigger('change'); // 触发子复选框change事件
        updateSelectedRecords(); // 直接更新计数
        updateBatchButtons();
    });
    
    // 单行复选框事件
    $(document).on('change', '.record-checkbox', function() {
        const allChecked = $('.record-checkbox:checked').length === $('.record-checkbox').length;
        $('#selectAll').prop('checked', allChecked);
        updateBatchButtons();
        updateSelectedCount(); // 同步更新计数
    });
    
    // 分页按钮点击事件
    $(document).on('click', '.pagination-btn', function() {
        const page = parseInt($(this).data('page'));
        if (!isNaN(page) && page !== currentPage) {
            currentPage = page;
            loadMediaList();
        }
    });
    
    // 批量操作按钮事件
    $('#batchClaimBtn').on('click', handleBatchClaim);
    $('#batchApproveBtn').on('click', handleBatchApprove);
    $('#batchRejectBtn').on('click', handleBatchReject);
    $('#batchReviewBtn').on('click', handleBatchReview);
    $('#closeReviewModal, #cancelReview').on('click', hideReviewModal);
    $('#confirmReview').on('click', handleConfirmReview);
    
    // 单行操作按钮事件
    $(document).on('click', '.claim-btn', function() {
        const contentId = $(this).data('id');
        handleClaim(contentId);
    });
    
    $(document).on('click', '.approve-btn', function() {
        const contentId = $(this).data('id');
        handleApprove(contentId);
    });
    
    $(document).on('click', '.reject-btn', function() {
        const contentId = $(this).data('id');
        handleReject(contentId);
    });
    
    $(document).on('click', '.review-btn', function() {
        const contentId = $(this).data('id');
        handleReview(contentId);
    });
    
    $(document).on('click', '.view-btn', function() {
        const contentId = $(this).data('id');
        viewDetail(contentId);
    });

    // 点击行选中/取消复选框
    $(document).on('click', '#contentTableBody tr', function(e) {
        // 修正：如果点击的元素是按钮、复选框等或其内部元素，不触发行选逻辑
        if (!$(e.target).closest('.record-checkbox, button, a, input, select').length) {
            const $checkbox = $(this).find('.record-checkbox');
            $checkbox.prop('checked', !$checkbox.prop('checked')).trigger('change');
        }
    });
}

// 页面加载完成后初始化
$(document).ready(function() {
    init();
});